<template>
  <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
    <a-form-model
      :model="info"
      ref="ruleForm"
      :rules="rules"
      @submit.native.prevent
      v-if="JSON.stringify(info) != '{}'"
    >
      <a-form-model-item label="题目名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="questionTitle">
        <a-input size="large" v-model="info.questionTitle" />
      </a-form-model-item>
      <a-form-model-item label="答对获取积分" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="rightCredit">
        <a-input-number size="large" style="width: 200px" v-model="info.rightCredit" />
      </a-form-model-item>
      <a-form-model-item label="答错获取积分" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="wrongCredit">
        <a-input-number size="large" style="width: 200px" v-model="info.wrongCredit" />
      </a-form-model-item>
      <template v-if="categoryKey != 'input' && categoryKey != 'textarea'">
        <a-form-model-item label="问题选项" :labelCol="labelCol" :wrapperCol="wrapperCol" required>
          <div class="question-item" v-for="(item, index) in info.selects" :key="index">
            <a-input v-model="item.selectContent" placeholder="请输入选项内容" size="large">
              <template slot="prefix">
                {{ letters[index] }}
              </template>
            </a-input>
            <a-tooltip>
              <template slot="title"> 若开启，选中此项作为答案 </template>
              <a-switch
                @change="
                  (checked) => {
                    item.isRight = checked ? 1 : 0
                    checkAnswer(item.isRight, index)
                  }
                "
                size="large"
                class="qswitch"
                :checked="item.isRight == 1 ? true : false"
              />
            </a-tooltip>
            <a-icon
              type="minus-square"
              style="font-size: 22px; margin-left: 5px"
              @click="removeSelect(index)"
              v-if="info.selects.length > 1"
            />
          </div>
        </a-form-model-item>
        <a-form-model-item :wrapperCol="{ span: 24 }" style="text-align: center">
          <a-button @click="addSelect" style="width: 200px" :disabled="disabled">
            <a-icon type="plus" />添加选项
          </a-button>
        </a-form-model-item>
      </template>
      <a-form-model-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
        {{ info.status ? '开启' : '关闭' }}
      </a-form-model-item>
      <a-form-model-item :wrapperCol="{ span: 24 }" style="text-align: center">
        <a-button
          htmlType="submit"
          type="primary"
          :loading="state.submitBtn"
          :disabled="state.submitBtn"
          @click="onSubmit"
          >保存</a-button
        >
        <a-button style="margin-left: 8px" @click="() => $router.go(-1)">取消</a-button>
      </a-form-model-item>
    </a-form-model>
  </a-card>
</template>

<script>
import pick from 'lodash.pick'
import { trim } from '@/utils/util'

export default {
  name: 'QuestionAdd',
  data() {
    return {
      id: this.$route.params.id || '',
      info: {},
      rules: {
        questionTitle: [{ required: true, message: '问题名称必填', trigger: ['blur', 'change'] }],
        rightCredit: [{ required: true, message: '答对获取积分必填', trigger: ['blur', 'change'] }],
        wrongCredit: [{ required: true, message: '答错获取积分必填', trigger: ['blur', 'change'] }]
      },
      state: {
        submitBtn: false
      },
      labelCol: { lg: { span: 7 }, sm: { span: 7 } },
      wrapperCol: { lg: { span: 10 }, sm: { span: 17 } },
      subjectCategories: [], // 题目类型
      categoryKey: '', // 题目类型标识
      disabled: false, // 添加选项按钮
      letters: [
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z'
      ]
    }
  },
  mounted() {
    // 获取信息
    this.formInit()
  },
  methods: {
    formInit() {
      // 获取信息
      if (this.id) {
        this.getInfo()
      } else {
        this.info = {
          questionCategoryId: 1,
          questionTitle: '',
          rightCredit: '',
          wrongCredit: '',
          selects: [{ selectContent: '', isRight: 0 }]
        }
      }
    },
    // 编辑角色信息
    getInfo() {
      this.$common.getInfo('/questions/' + this.id).then((data) => {
        if (data.code === 200) {
          const result = data.data
          const formData = pick(result, [
            'questionId',
            'questionCategoryId',
            'questionCategoryKey',
            'questionTitle',
            'rightCredit',
            'wrongCredit',
            'selects'
          ])
          for (var [k, v] of Object.entries(formData)) {
            if (k === 'selects') {
              v = v.length > 0 ? v : [{ selectContent: '', isRight: 0 }]
            }
            this.$set(this.info, k, v)
          }
          this.categoryKey = formData.questionCategoryKey
        } else {
          this.$message.error(data.msg)
          // 跳转到目的路由
          this.$router.go(-1)
        }
      })
    },
    // 问题类型
    changeCategory(record) {
      this.categoryKey = record.categoryKey
    },
    // 添加选项
    addSelect() {
      const len = this.info.selects.length
      var err = 0
      if (len >= 11) {
        this.disabled = true
        this.$message.error('最多添加12个选项')
      } else {
        if (len > 0) {
          if (trim(this.info.selects[len - 1]['selectContent']) === '') {
            this.$message.error('请填写选项')
            err++
          }
        }
        if (err === 0) this.info.selects.push({ selectContent: '', isRight: 0 })
      }
    },
    // 删除选项
    removeSelect(index) {
      const len = this.info.selects.length
      if (index <= len - 1) {
        this.info.selects.splice(index, 1)
        if (len - 1 < 10) {
          this.disabled = false
        }
      }
    },
    // 检测答案
    checkAnswer(val, index) {
      console.log(val, index)
      if (val === 1 && this.info.selects?.length > 1) {
        this.info.selects.forEach((item, i) => {
          console.log(item, i)
          if (i !== index && item.isRight === 1) {
            item.isRight = 0
          }
        })
      }
    },
    // 提交
    onSubmit() {
      const { state, handleFormData } = this
      state.submitBtn = true
      // 验证表单
      this.$refs.ruleForm.validate((valid) => {
        var info = JSON.parse(JSON.stringify(this.info))
        if (this.categoryKey === 'textarea') {
          info.selects = []
        } else {
          const len = info.selects.length
          if (len > 0) {
            if (trim(info.selects[len - 1].selectContent) === '') {
              if (len > 1) {
                info.selects.splice(len - 1, 1)
              } else {
                valid = false
                this.$message.error('请填写选项')
              }
            }
          } else {
            valid = false
            this.$message.error('请填写选项')
          }
        }
        if (valid) {
          const answerArr = info.selects.filter((item) => (item.isRight === 1))
          console.log(answerArr)
          if (answerArr.length === 0) {
            valid = false
            this.$message.error('请选择正确答案')
          }
        }
        if (valid) {
          this.id ? handleFormData('/questions/' + this.id, info) : handleFormData('/questions/add', info)
        } else {
          setTimeout(() => {
            state.submitBtn = false
          }, 600)
        }
      })
    },
    // 表单数据处理
    handleFormData(url, info) {
      this.$common
        .handlePost(url, info)
        .then((res) => {
          if (res.code === 200) {
            this.$message.success(res.msg)
            // 跳转到目的路由
            this.$router.go(-1)
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(() => {
          this.$notification.error({
            message: '错误',
            description: '请求信息失败，请重试'
          })
        })
        .finally(() => {
          this.state.submitBtn = false
        })
    }
  }
}
</script>

<style lang="less" scoped>
.question-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  .qswitch {
    margin-left: 5px;
  }
}
.question-item:nth-last-child(1) {
  margin-bottom: 0;
}
</style>
